package com.crm.service.impl;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveAction;
import java.util.concurrent.atomic.AtomicInteger;

import javax.annotation.PostConstruct;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.crm.dao.BizBrandMapper;
import com.crm.dao.BizInfosBelongMapper;
import com.crm.dao.BizProjectLevelMapper;
import com.crm.dao.BizProjectMapper;
import com.crm.dao.ConsultInfoManageIllegalMapper;
import com.crm.dao.ConsultInfoManageMapper;
import com.crm.dao.SysDepartmentMapper;
import com.crm.dao.SysStudentAttrMapper;
import com.crm.handler.ConsultInfoImprotException;
import com.crm.model.BizBrand;
import com.crm.model.BizInfosBelong;
import com.crm.model.BizProject;
import com.crm.model.BizProjectLevel;
import com.crm.model.ConsultInfoManage;
import com.crm.model.ConsultInfoManageIllegal;
import com.crm.model.SysDepartment;
import com.crm.model.SysStudentAttr;
import com.crm.model.SysUser;
import com.crm.model.entity.ConsultInfoValueKey;
import com.crm.service.ConsultInfoManageIllegalService;
import com.crm.util.BeanUtil;
import com.crm.util.CheckUtil;
import com.crm.util.SessionModel;
import com.crm.util.SessionUtils;
@Service
public class ConsultInfoManageIllegalServiceImpl extends BaseServiceImpl<ConsultInfoManageIllegal>
		implements ConsultInfoManageIllegalService {
	@Autowired
	private ConsultInfoManageMapper  consultInfoManageMapper;
	@Autowired
	private ConsultInfoManageIllegalMapper infoManageIllegalMapper;
	@Autowired
	private SysDepartmentMapper deptMapper;
	@Autowired
	private BizBrandMapper brandMapper;
	@Autowired
	private SysStudentAttrMapper stuAttrMapper;
	@Autowired
	private BizProjectMapper projectMapper;
	@Autowired
	private BizProjectLevelMapper projectLevelMapper;
	@Autowired
	private BizInfosBelongMapper infoBelongMapper;
	@Autowired
	private ApplicationContext context;
	private ConsultInfoManageIllegalService consultIllegalServProxySelf;
	@PostConstruct
	private void setSelf() {
		consultIllegalServProxySelf = context.getBean(ConsultInfoManageIllegalService.class);
	}
	@Override
	public Map<String,Object> batchConsultInfoEnterFromExcel(List<ConsultInfoManageIllegal> infoIllegalList) {
		Map<String,Object> resultMap = new HashMap<>();
		int successRow = 0;//成功录入的行数
		int position = 2;// Excel中第三行为数据
		for(ConsultInfoManageIllegal illegalInfo:infoIllegalList){
			position++;
			try {
				SysDepartment dept = new SysDepartment();
				dept.setType(3);
				//分校集合
				List<SysDepartment> deptList = deptMapper.selectAllByWhere(dept);
				//品牌集合
				List<BizBrand> brandList = brandMapper.selectAllByWhere(new BizBrand());
				//咨询者类型 媒体来源信息集合
				List<SysStudentAttr> stuAttrList =stuAttrMapper.selectAllByWhere(new SysStudentAttr());
				//项目集合
				List<BizProject> projectList = projectMapper.selectAllByWhere(new BizProject());
				ConsultInfoManage info = new ConsultInfoManage();
				boolean flag =checkConsultInfo(resultMap, position,info,illegalInfo,deptList, brandList, stuAttrList,projectList);
				if(flag){
					info=copyProperties(illegalInfo, info);
					if(info==null){
						resultMap.put(String.valueOf(position), "转换信息错误");
						continue;
					}else{
						consultIllegalServProxySelf.insertConsultInfoFromExcel(info);
						successRow++;
					}
				}else{
					String illegalReason = (String) resultMap.get(String.valueOf(position));
					illegalInfo.setIllegalReason(illegalReason);
					saveOrUpdate(illegalInfo);
				}
			}catch(ConsultInfoImprotException improtE){
				resultMap.put(String.valueOf(position), improtE==null?"录入信息异常":improtE.getMessage());
			} catch (Exception e) {
				e.printStackTrace();
				resultMap.put(String.valueOf(position), "数据异常");
			}
			
		}
		resultMap.put("success", "共有"+infoIllegalList.size()+"条用户数据,成功录入"+successRow+"个用户");
		return resultMap;
	}
	

	@Override
	public Map<String, Object> batchConsultInfoEnterFromExcelThroughThreadPool(
			List<ConsultInfoManageIllegal> infoIllegalList) {
		AtomicInteger successRow = new AtomicInteger(0);
		ConcurrentHashMap<String, Object> retMap = new ConcurrentHashMap<String, Object>();
		final CountDownLatch countDownLatch = new CountDownLatch(infoIllegalList.size());
		ConsultInsertJoinPool insertJoinPool = new ConsultInsertJoinPool(infoIllegalList, retMap, successRow, countDownLatch);
		insertJoinPool.submit();
		retMap.put("success", "共有"+infoIllegalList.size()+"条用户数据,成功录入"+successRow.get()+"个用户");
		return retMap;
	} 
	/**
	 * 该方法仅供batchConsultInfoEnterFromExcel使用,用于从Excel录入的信息
	 * @param t
	 */
	@Override
	@Transactional(propagation = Propagation.REQUIRES_NEW,rollbackFor = { Exception.class }) 
	public void insertConsultInfoFromExcel(ConsultInfoManage t) throws ConsultInfoImprotException {
		SysUser sy = (SysUser)SessionUtils.get(SessionModel.SESSION_USER);
		t.setInfoManageId(UUID.randomUUID().toString());
		t.setSourceType(new Byte("3"));
		t.setCreateDate(new Date());
		t.setCreateUserId(sy.getUserId());
		t.setCreateUserName(sy.getRealName());
		t.setModifyUserId(sy.getUserId());
		t.setModifyUserName(sy.getRealName());
		t.setModifyDate(new Date());
		consultInfoManageMapper.insert(t);
	}
	/**
	 * 保存或更新错误的工作咨询量信息
	 * @param infoIllegal
	 */
	private void saveOrUpdate (ConsultInfoManageIllegal infoIllegal){
		SysUser sy = (SysUser)SessionUtils.get(SessionModel.SESSION_USER);
		infoIllegal.setModifyUserId(sy.getUserId());
		infoIllegal.setModifyUserName(sy.getRealName());
		infoIllegal.setModifyDate(new Date());
		infoIllegal.setInfoManageId(UUID.randomUUID().toString());
		ConsultInfoManageIllegal queryConsult = new ConsultInfoManageIllegal();
		queryConsult.setProjectName(infoIllegal.getProjectName());
		queryConsult.setBrandName(infoIllegal.getBrandName());
		queryConsult.setStudentPhone(infoIllegal.getStudentPhone());
		List<ConsultInfoManageIllegal> queryConsultList =infoManageIllegalMapper.selectView(queryConsult);
		if(queryConsultList.size()>0){
			infoIllegal.setInfoManageId(queryConsultList.get(0).getInfoManageId());
			infoManageIllegalMapper.updateByPrimaryKey(infoIllegal);
		}else{
			infoIllegal.setCreateUserId(sy.getUserId());
			infoIllegal.setCreateUserName(sy.getRealName());
			infoIllegal.setCreateDate(new Date());
			infoManageIllegalMapper.insert(infoIllegal);
		}
		
	}
	/**
	 * 该方法仅供batchConsultInfoEnterFromExcel使用,用于从Excel录入的信息
	 * @param map
	 * @param position
	 * @param info
	 * @param deptList
	 * @param brandList
	 * @param stuAttrList
	 * @param projectList
	 * @return
	 */
	private boolean checkConsultInfo(Map<String,Object> map,int position,ConsultInfoManage info,ConsultInfoManageIllegal illegalInfo,List<SysDepartment> deptList,List<BizBrand> brandList,List<SysStudentAttr> stuAttrList,List<BizProject> projectList){
		boolean flag = false;
		String departmentName1 = illegalInfo.getDepartmentName1();//信息归属地
		String brandName = illegalInfo.getBrandName();//品牌名称
		String studentAttrName2 = illegalInfo.getStudentAttrName2();//咨询者类型
		String studentAttrName1 = illegalInfo.getStudentAttrName1();//媒体来源
		String studentPhone= illegalInfo.getStudentPhone();//电话
		String projectName=illegalInfo.getProjectName();//咨询课程
		String projectLevelName= illegalInfo.getProjectLevelName();//课程级别
		String highestEducation =illegalInfo.getHighestEducation();//最高学历
		String age = illegalInfo.getAge();//年龄
		
		if(StringUtils.isNotBlank(departmentName1)){
			for(SysDepartment dept:deptList){
				if(dept.getFullName()!=null&&dept.getFullName().trim().equals(departmentName1)){
					flag = true;
					info.setDepartmentName1(departmentName1);
					info.setDepartmentId1(dept.getDepartmentId());
					break;
				}
			}
		}else{
			flag = true;
		}		
		
		if(!flag){
			map.put(String.valueOf(position), "信息归属地未匹配");
			return flag;
		}
		flag = false;
		if(StringUtils.isNotBlank(brandName)){
			for(BizBrand brand:brandList){
				if(brand.getBrandName()!=null&&brand.getBrandName().trim().equals(brandName)){
					flag = true;
					info.setBrandName(brandName);
					info.setBrandId(brand.getBrandId());
					break;
				}
			}
		}else{
			flag = true;
		}
		
		if(!flag){
			map.put(String.valueOf(position), "信息归属地未匹配");
			return flag;
		}
		flag = false;
		if(StringUtils.isNotBlank(studentAttrName2)){
			for(SysStudentAttr stuAttr:stuAttrList){
				if(stuAttr.getTypeName()!=null&&stuAttr.getTypeName().trim().equals(studentAttrName2)&&Integer.valueOf(2).equals(stuAttr.getAttrType())){
					flag = true;
					info.setStudentAttrName2(studentAttrName2);
					info.setStudentAttrId2(stuAttr.getStudentAttrId());
					break;
				}
			}
		}else{
			flag = true;
		}
		
		if(!flag){
			map.put(String.valueOf(position), "咨询者类型未匹配");
			return flag;
		}
		/*flag = false;
		if("在线有效".equals(studentAttrName2)&&StringUtils.isBlank(conversation)){
			map.put(String.valueOf(position), "咨询者类型为在线有效,对话记录不能为空");
			return flag;
		}*/
		flag = false;
		if(StringUtils.isNotBlank(highestEducation)){
			for(SysStudentAttr stuAttr:stuAttrList){
				if(stuAttr.getTypeName()!=null&&stuAttr.getTypeName().trim().equals(highestEducation)&&Integer.valueOf(3).equals(stuAttr.getAttrType())){
					flag = true;
					info.setHighestEducation(highestEducation);
					break;
				}
			}
		}else{
			flag = true;
		}
		
		if(!flag){
			map.put(String.valueOf(position), "最高学历填写错误");
			return flag;
		}
		
		flag = false;
		if(StringUtils.isNotBlank(studentAttrName1)){
			for(SysStudentAttr stuAttr:stuAttrList){
				if(stuAttr.getTypeName()!=null&&stuAttr.getTypeName().trim().equals(studentAttrName1)&&Integer.valueOf(1).equals(stuAttr.getAttrType())){
					flag = true;
					info.setStudentAttrName1(studentAttrName1);
					info.setStudentAttrId1(stuAttr.getStudentAttrId());
					break;
				}
			}
		}else{
			flag = true;
		}
		if(!flag){
			map.put(String.valueOf(position), "媒体来源未匹配");
			return flag;
		}
		flag = false;
		if(StringUtils.isNotBlank(projectName)){
			for(BizProject project:projectList){
				if(project.getFullName().trim()!=null&&project.getFullName().equals(projectName)){
					flag = true;
					info.setProjectName(projectName);
					info.setProjectId(project.getProjectId());
					break;
				}
			}
		}else{
			flag = true;
		}
		
		if(!flag){
			map.put(String.valueOf(position), "咨询课程未匹配");
			return flag;
		}
		BizProjectLevel projectLevel = new BizProjectLevel();
		projectLevel.setProjectId(info.getProjectId());
		List<BizProjectLevel> projectLevelList= projectLevelMapper.selectByUs(projectLevel);
		flag = false;
		if(StringUtils.isNotBlank(projectLevelName)){
			for(BizProjectLevel proLevel:projectLevelList){
				if(proLevel.getLevelTitle()!=null&&proLevel.getLevelTitle().equals(projectLevelName)){
					flag = true;
					info.setProjectLevelName(projectLevelName);
					info.setProjectLevelId(proLevel.getProjectLevelId());
					break;
				}
			}
		} else {
			flag = true;
		}
		
		if(!flag){
			map.put(String.valueOf(position), "该咨询课程下的课程级别未匹配");
			return flag;
		}
		if(StringUtils.isNotBlank(age)){
			if(!CheckUtil.Number(age)||age.length()>3){
				flag = false;
				map.put(String.valueOf(position), "年龄错误");
				return flag;
			}
		}
		
		
		ConsultInfoManage queryConsult = new ConsultInfoManage();
		queryConsult.setProjectId(info.getProjectId());
		queryConsult.setBrandId(info.getBrandId());
		queryConsult.setStudentPhone(studentPhone);
		List<ConsultInfoManage> queryConsultList =consultInfoManageMapper.selectView(queryConsult);
		if(queryConsultList.size()>0){
			flag = false;
			map.put(String.valueOf(position), "在"+DateFormatUtils.format(queryConsultList.get(0).getCreateDate(), "yyyy-MM-dd HH:mm:ss")+","+queryConsultList.get(0).getCreateUserName()+"已创建该咨询课程和招生品牌的咨询量，请核对后输入！");
			return flag;
		}
		StringBuilder brandSchool = new StringBuilder();
		brandSchool.append("^\\[[[:print:]]*\\{\\\"brand\\\"\\:\\\"");
		brandSchool.append(info.getBrandId());
		brandSchool.append("\\\"\\,\\\"school\\\"\\:\\[[a-zA-Z0-9\\-\\,\\\"]*\\\"");
		brandSchool.append(info.getDepartmentId1());
		brandSchool.append("\\\"[a-zA-Z0-9\\-\\,\\\"]*\\]\\}[[:print:]]*\\]$");
		BizInfosBelong infosBelong = new BizInfosBelong();
		infosBelong.setProjects(info.getProjectId());
		infosBelong.setBrandSchool(brandSchool.toString());
		List<BizInfosBelong> infoBelongList=infoBelongMapper.selectAllByWhere(infosBelong);
		if(infoBelongList.size()>0){
			info.setDepartmentId2(infoBelongList.get(0).getDepartmentId());
			info.setDepartmentName2(infoBelongList.get(0).getSysDepartment().getFullName());
		}else{
			info.setDepartmentId2(info.getDepartmentId1());
			info.setDepartmentName2(info.getDepartmentName1());
		}
		info.setStatus(new Byte("1"));
		SysDepartment sd = deptMapper.selectByPrimaryKey(info.getDepartmentId2());
		if(sd.getType()==3){
			info.setTypeFrom("3");
		}else{
			info.setTypeFrom("1");
		}
		ConsultInfoManage queryCim = consultInfoManageMapper.getTopOne(info);
		if(queryCim!=null){
			if(queryCim.getCounselorId()!=null){
				info.setCounselorId(queryCim.getCounselorId());
				info.setCounselor(queryCim.getCounselor());
				info.setStatus(new Byte("2"));
			}
		}
		return flag;
	}
	/**
	 * 复制属性值到ConsultInfoManage
	 * @param illegalInfo
	 * @param info
	 */
	private ConsultInfoManage copyProperties(ConsultInfoManageIllegal illegalInfo,ConsultInfoManage info){
		Map<String,Object> map =BeanUtil.transBean2Map(illegalInfo);
		if(map.containsKey("studentSex")){
			map.put("studentSex", "男".equals(illegalInfo.getStudentSex())?Byte.valueOf("0"):"女".equals(illegalInfo.getStudentSex())?Byte.valueOf("0"):null);
		}
		Iterator<String> iterator= map.keySet().iterator();
		while(iterator.hasNext()){
			String key = iterator.next();
			if(!ConsultInfoValueKey.consultHeadtMap.containsValue(key)){
				iterator.remove();
			}
		}
		try {
			Field[] fields =illegalInfo.getClass().getDeclaredFields();
			Iterator<Entry<String,String>> entryIterator=ConsultInfoValueKey.consultHeadtMap.entrySet().iterator();
			while(entryIterator.hasNext()){
				Entry<String,String> entry = entryIterator.next();
				for(int i=0;i<fields.length;i++){
					if(fields[i].getName().equals(entry.getValue())){
						String name = fields[i].getName().replaceFirst(fields[i].getName().substring(0, 1), fields[i].getName().substring(0, 1).toUpperCase());
						
						if("studentSex".equals(fields[i].getName())){
							Method method =info.getClass().getDeclaredMethod("set" + name,Byte.class);
							method.setAccessible(true);
							method.invoke(info, map.get("studentSex")==null?null:Byte.valueOf((Byte)map.get("studentSex")));
						}else{
							Method method =info.getClass().getDeclaredMethod("set" + name,String.class);
							method.setAccessible(true);
							method.invoke(info, map.get(fields[i].getName()));
						}
						
					}
				}
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			info=null;
		}
		return info;
	}
	@Override
	public String transfer(ConsultInfoManageIllegal infoIllegal)  {
		String status ="success";
		infoIllegal = infoManageIllegalMapper.selectByPrimaryKey(infoIllegal.getInfoManageId());
		SysDepartment dept = new SysDepartment();
		dept.setType(3);
		//分校集合
		List<SysDepartment> deptList = deptMapper.selectAllByWhere(dept);
		//品牌集合
		List<BizBrand> brandList = brandMapper.selectAllByWhere(new BizBrand());
		//咨询者类型 媒体来源信息集合
		List<SysStudentAttr> stuAttrList =stuAttrMapper.selectAllByWhere(new SysStudentAttr());
		//项目集合
		List<BizProject> projectList = projectMapper.selectAllByWhere(new BizProject());
		ConsultInfoManage info = new ConsultInfoManage();
		Map<String,Object> retMap = new HashMap<>();
		boolean flag =checkConsultInfo(retMap, 1,info,infoIllegal,deptList, brandList, stuAttrList,projectList);
		if(flag){
			info=copyProperties(infoIllegal, info);
			if(info!=null){
				try {
					consultIllegalServProxySelf.insertConsultInfoFromExcel(info);
				} catch (Exception e) {
					e.printStackTrace();
					status = "failure";
				}
				infoManageIllegalMapper.deleteByPrimaryKey(infoIllegal.getInfoManageId());
			}else{
				infoManageIllegalMapper.updateByPrimaryKey(infoIllegal);
			}
		}else{
			status = (String) retMap.get("1");
		}
		return status;
	}
	@Override
	public String insertConsultAnddelIllegalINfo(ConsultInfoManage t) {
		SysUser sy = (SysUser)SessionUtils.get(SessionModel.SESSION_USER);
		String uuId = t.getInfoManageId();
		t.setInfoManageId(UUID.randomUUID().toString());
		t.setSourceType(new Byte("3"));
		t.setCreateDate(new Date());
		t.setCreateUserId(sy.getUserId());
		t.setCreateUserName(sy.getRealName());
		t.setModifyUserId(sy.getUserId());
		t.setModifyUserName(sy.getRealName());
		t.setModifyDate(new Date());
		
		ConsultInfoManage queryConsult = new ConsultInfoManage();
		queryConsult.setProjectId(t.getProjectId());
		queryConsult.setBrandId(t.getBrandId());
		queryConsult.setStudentPhone(t.getStudentPhone());
		List<ConsultInfoManage> queryConsultList =consultInfoManageMapper.selectView(queryConsult);
		if(queryConsultList.size()>0){
			return "failure";
		}
		
		StringBuilder brandSchool = new StringBuilder();
		brandSchool.append("^\\[[[:print:]]*\\{\\\"brand\\\"\\:\\\"");
		brandSchool.append(t.getBrandId());
		brandSchool.append("\\\"\\,\\\"school\\\"\\:\\[[a-zA-Z0-9\\-\\,\\\"]*\\\"");
		brandSchool.append(t.getDepartmentId1());
		brandSchool.append("\\\"[a-zA-Z0-9\\-\\,\\\"]*\\]\\}[[:print:]]*\\]$");
		BizInfosBelong infosBelong = new BizInfosBelong();
		infosBelong.setProjects(t.getProjectId());
		infosBelong.setBrandSchool(brandSchool.toString());
		List<BizInfosBelong> infoBelongList=infoBelongMapper.selectAllByWhere(infosBelong);
		if(infoBelongList.size()>0){
			t.setDepartmentId2(infoBelongList.get(0).getDepartmentId());
			t.setDepartmentName2(infoBelongList.get(0).getSysDepartment().getFullName());
		}else{
			t.setDepartmentId2(t.getDepartmentId1());
			t.setDepartmentName2(t.getDepartmentName1());
		}
		t.setStatus(new Byte("1"));
		SysDepartment sd = deptMapper.selectByPrimaryKey(t.getDepartmentId2());
		if(sd.getType()==3){
			t.setTypeFrom("3");
		}else{
			t.setTypeFrom("1");
		}
		ConsultInfoManage queryCim = consultInfoManageMapper.getTopOne(t);
		if(queryCim!=null){
			if(queryCim.getCounselorId()!=null){
				t.setCounselorId(queryCim.getCounselorId());
				t.setCounselor(queryCim.getCounselor());
				t.setStatus(new Byte("2"));
			}
		}
		
		consultInfoManageMapper.insert(t);
		infoManageIllegalMapper.deleteByPrimaryKey(uuId);
		return "success";
	}
	/**
	 * 
	 * @author ljc
	 *该类只服务于批量导入的咨询工作台信息
	 */
	class ConsultInsertJoinPool {
		
		//分校集合
		private  List<SysDepartment> deptList;  
		//品牌集合
		private  List<BizBrand> brandList; 
		//咨询者类型 媒体来源信息集合
		private  List<SysStudentAttr> stuAttrList;
		//项目集合
		private  List<BizProject> projectList;
		//工作池
		private  ForkJoinPool forkJoinPool;
		//待插入的信息
		private List<ConsultInfoManageIllegal> tasklist;
		//存放每行信息的保存结果
		private ConcurrentHashMap<String, Object> retMap;
		//成功的行数
		private AtomicInteger successRow;
		
		private  CountDownLatch countDownLatch;
		
		ConsultInsertJoinPool(List<ConsultInfoManageIllegal> tasklist,ConcurrentHashMap<String, Object> retMap,AtomicInteger successRow,CountDownLatch countDownLatch){
			InfoSource();
			this.tasklist = tasklist;
			this.retMap = retMap==null?new ConcurrentHashMap<>():retMap;
			this.successRow = successRow;
			this.countDownLatch = countDownLatch;
			forkJoinPool = new ForkJoinPool(Runtime.getRuntime().availableProcessors());
			
		}
		private void InfoSource(){//数据源
			SysDepartment dept = new SysDepartment();
			dept.setType(3);
			deptList =deptMapper.selectAllByWhere(dept);
			brandList = brandMapper.selectAllByWhere(new BizBrand());
			stuAttrList=stuAttrMapper.selectAllByWhere(new SysStudentAttr());
			projectList= projectMapper.selectAllByWhere(new BizProject());
		}
		void submit(){
			forkJoinPool.submit(new ConsultInsertTask(0, tasklist.size(), tasklist, deptList, brandList, stuAttrList, projectList,retMap,successRow,countDownLatch));
			try {
				countDownLatch.await();
			} catch (InterruptedException e) {
			}
			forkJoinPool.shutdown();
		}
		  
	}
	
	/**
	 * 
	 * @author ljc
	 *该类只服务于批量导入的咨询工作台信息
	 */
	@SuppressWarnings("serial")
	class ConsultInsertTask extends RecursiveAction{
		//每次插入最多五十个
		private static final int threshold = 50;
		
		private int  start;
		
		private int  end;
		
		private List<ConsultInfoManageIllegal> tasklist;
	
		//分校集合
		private  List<SysDepartment> deptList;  
		//品牌集合
		private  List<BizBrand> brandList; 
		//咨询者类型 媒体来源信息集合
		private  List<SysStudentAttr> stuAttrList;
		//项目集合
		private  List<BizProject> projectList;
		//存储异常信息
		private  ConcurrentHashMap<String, Object> retMap;
		//成功的行数
		private AtomicInteger successRow;
		
		private  CountDownLatch countDownLatch;
		
		 ConsultInsertTask(int start,int end,List<ConsultInfoManageIllegal> tasklist,List<SysDepartment> deptList,List<BizBrand> brandList,List<SysStudentAttr> stuAttrList,List<BizProject> projectList,ConcurrentHashMap<String, Object> retMap,AtomicInteger successRow,CountDownLatch countDownLatch) {
			this.start = start;
			this.end = end;
			this.tasklist=tasklist;
			this.deptList = deptList;
			this.brandList = brandList;
			this.stuAttrList = stuAttrList;
			this.projectList = projectList;
			this.retMap = retMap;
			this.successRow = successRow;
			this.countDownLatch = countDownLatch;
		}

		@Override
		protected void compute() {
			if((end-start)<=threshold){
				int position=0;
				for (int i = start; i < end; i++) {
					try {
						ConsultInfoManage info = new ConsultInfoManage();
						position = i + 3;
						ConsultInfoManageIllegal illegalInfo = tasklist.get(i);
						boolean flag = checkConsultInfo(retMap, position, info, illegalInfo, deptList, brandList,
								stuAttrList, projectList);
						if (flag) {
							info = copyProperties(tasklist.get(i), info);
							if (info == null) {
								retMap.put(String.valueOf(position), "转换信息错误");
								continue;
							} else {
								consultIllegalServProxySelf.insertConsultInfoFromExcel(info);
								successRow.incrementAndGet();
							}
						} else {
							String illegalReason = (String) retMap.get(String.valueOf(position));
							illegalInfo.setIllegalReason(illegalReason);
							saveOrUpdate(illegalInfo);
						}
					} catch (ConsultInfoImprotException improtE) {
						retMap.put(String.valueOf(position), improtE == null ? "录入信息异常" : improtE.getMessage());
					} catch (Exception e) {
						e.printStackTrace();
						retMap.put(String.valueOf(position), "数据异常");
					} finally {
						countDownLatch.countDown();
					}
				}
				
			}else{
				 int middle = (start + end) / 2;
				 ConsultInsertTask leftTask = new ConsultInsertTask(start, middle, tasklist, deptList, brandList, stuAttrList, projectList,retMap,successRow,countDownLatch);
				 ConsultInsertTask rightTask = new ConsultInsertTask(middle, end, tasklist, deptList, brandList, stuAttrList, projectList,retMap,successRow,countDownLatch);
				 leftTask.fork();
				 rightTask.fork();
			}
		}
		
	}

	

}
